package servlet;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import org.apache.commons.fileupload.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.io.FilenameUtils;

import Database.DBConnection;

/**
 * Servlet implementation class SingleNewForm
 */
public class SingleNewForm extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SingleNewForm() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String procedureIDVar = "";
		String formNameVar = "";
		String effectiveDateVar = "";
		String reformattedStr = "";
		String serverPath = "";
		String filename = "";

		try {
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// Process regular form field (input
					// type="text|radio|checkbox|etc", select, etc).
					String fieldname = item.getFieldName();
					String fieldvalue = item.getString();
					if (fieldname.equalsIgnoreCase("Pid")) {
						procedureIDVar = fieldvalue;
					} else if (fieldname.equalsIgnoreCase("FormName")) {
						formNameVar = fieldvalue;
					} else if (fieldname.equalsIgnoreCase("effectivedate")) {
						effectiveDateVar = fieldvalue;
						SimpleDateFormat odf = new SimpleDateFormat("dd MMM yy");
						SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
						try {
							reformattedStr = sdf.format(odf
									.parse(effectiveDateVar));
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						System.out.println(reformattedStr);
						int ret = insertRecordToDB(serverPath + filename,
								reformattedStr, formNameVar, procedureIDVar);
						System.out.println(ret + " records updated!");
					}
				} else {
					// Process form file field (input type="file").
					String fieldname = item.getFieldName();
					filename = FilenameUtils.getName(item.getName());
					InputStream filecontent = item.getInputStream();
					serverPath = getServerPath(procedureIDVar);
					String fullServerPath = request.getServletContext()
							.getRealPath("/") + serverPath;
					File filePath = new File(fullServerPath);
					System.out.println("Server folder path: " + fullServerPath);
					if (!filePath.exists()) {
						filePath.mkdirs();
					}
					int read = 0;
					FileOutputStream outputStream = new FileOutputStream(
							fullServerPath + filename);
					try {

						byte[] bytes = new byte[1024];

						while ((read = filecontent.read(bytes)) != -1) {
							outputStream.write(bytes, 0, read);
						}
					} catch (Exception ex2) {
						System.out.println(ex2);
					} finally {
						if (outputStream != null) {
							outputStream.flush();
							outputStream.close();
						}
						if (filecontent != null) {
							filecontent.close();
						}
					}

				}
			}
		} catch (FileUploadException e) {
			System.out.println(e);
			request.getRequestDispatcher("Proc_NewForm.jsp?result=-1").forward(
					request, response);
			// throw new ServletException("Cannot parse multipart request.", e);

		}
		System.out.println("Forwarding page...");
		request.getRequestDispatcher("Proc_NewForm.jsp?result=1").forward(
				request, response);

	}

	private String getServerPath(String procIDVar) {
		Connection connection1st = null;
		Statement statement1st = null;
		ResultSet rs1st = null;
		String CategoryVar = "";
		String CodeVar = "";
		String ProcessNameVar = "";
		// String ProcedureNameVar="";
		try {

			connection1st = DBConnection.connect(true);
			statement1st = connection1st.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			String QueryString1st = "SELECT * from qmsdb.processes WHERE idProc='"
					+ procIDVar + "'";
			rs1st = statement1st.executeQuery(QueryString1st);

			while (rs1st.next()) {
				CategoryVar = rs1st.getString("Category");
				CodeVar = rs1st.getString("Code");
				ProcessNameVar = rs1st.getString("ProcessName");
				// ProcedureNameVar = rs1st.getString("ProcedureName");
			}

			// close all the connections.

		} catch (Exception ex) {
			System.out.println(ex);
		} finally {
			try {
				if (rs1st != null)
					rs1st.close();
				if (statement1st != null)
					statement1st.close();
				if (connection1st != null)
					connection1st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String serverPath = "WordDoc_Proccesses/" + CategoryVar + "/"
				+ ProcessNameVar + "/Form/" + CodeVar + "/";
		System.out.println("Server folder path: " + serverPath);
		return serverPath;
	}

	private int insertRecordToDB(String fullFilePath, String dateUpdate,
			String formName, String procedureID) {
		Connection con = null;
		PreparedStatement stmt = null;
		int j1 = 0;
		try {
			String sql = "";
			con = DBConnection.connect(true);
			sql = "INSERT INTO forms (FormURL, FormLastUpdate, FormName, idProc) Values (?, ?, ?, ?)";
			stmt = con.prepareStatement(sql);
			stmt.setString(1, fullFilePath);
			stmt.setString(2, dateUpdate);
			stmt.setString(3, formName);
			stmt.setString(4, procedureID);
			j1 = stmt.executeUpdate();
		} catch (SQLException ex) {
			System.out.println(ex);
		} finally {
			try {
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return j1;
	}

}
